//
//  SEGParkMenuListManager.m
//  SEGMenus
//
//  Created by 乔杨 on 2020/12/2.
//

#import "SEGParkMenuListManager.h"

#if __has_include(<CommonMediator/SEGMediatorHeader.h>)
#import <CommonMediator/SEGMediatorHeader.h>
#else
#import "SEGMediatorHeader.h"
#endif
#if __has_include(<Commom/SEGProfileManager.h>)
#import <Commom/SEGProfileManager.h>
#else
#import "SEGProfileManager.h"
#endif
#if __has_include(<Commom/SEGCommunityLocationView.h>)
#import <Commom/SEGCommunityLocationView.h>
#else
#import "SEGCommunityLocationView.h"
#endif

#import "SEGMenuListCacheManager.h"
#import "SEGQuiztypelistManager.h"
#import "SEGQueryauthinfoManager.h"
#import "SEGParkMenuWidgetType.h"

#import "SEGParkMenuTabBarModel.h"
#import "SEGParkMenuPageModel.h"
#import "SEGMenuQuizTypeList.h"
#import "SEGMenuSideslipViewModel.h"

@interface SEGParkMenuListManager ()

/// 广告模型
@property (nonatomic, strong) SEGAdvertisementViewModel *advertisementData;
/// 老PGC模型
@property (nonatomic, strong) SEGMenuSideslipViewModel *oldPgcData;

@end

@implementation SEGParkMenuListManager

static NSArray<SEGMenuListModel *> *_menuListTab = nil;

#pragma mark - tabBar菜单
/// 请求菜单底部tabBar
/// @param completion 回调
+ (void)park_requestNetworkMenuForTabBarCompletion:(void(^)(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage))completion {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/terrace-service-app/navigate/selectNavigateByAppId", nil];
    NSDictionary *param = @{@"communityId" : kAccountCommunityID ?: @""};
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:param completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        // 模型转换
        NSArray<SEGMenuListModel *> *data = [SEGParkMenuListManager inner_responseTabBarDataWithAction:@"Tab" isSuccessed:isSuccessed result:result];
        // 无数据
        if (!data && data.count <= 0) {
            if (completion) completion(NO, nil, codeType, error.localizedDescription);
            return;
        }
        
        // 保存菜单父子级关系，用于打红点
        [[SEGUhomeMediator sharedInstance] seg_saveMenuList:@{@"array":data, @"parentsSid":@"0"}];
        
        SEGParkMenuListManager.menuListTab = data;
        if (completion) completion(isSuccessed, result, codeType, error.localizedDescription);
        return;
    }];
}

#pragma mark - 页面菜单
/// 请求本地缓存菜单页面数据
/// @param action 页面编码
/// @param settingsId  导航菜单id
/// @param type 广告类型
/// @param completion 回调
- (void)park_requestLocalMenuForPageWithAction:(NSString *)action settingsId:(NSString *)settingsId positionType:(SEGAdvlistType)type completion:(park_menu_block)completion {
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.uhome_park.menu.local", DISPATCH_QUEUE_CONCURRENT);
    
    __block BOOL _hasNewPGC = NO, _hasAD = NO, _hasCommonMenu = NO;
    
    dispatch_barrier_async(queue, ^{
        // 获取菜单本地缓存
        self.menuListDataArr = [SEGMenuListCacheManager sany_menuCache_getMenuListDataWithAction:action];
        
        // 红点逻辑
        [self inner_bindRedDotWithData:self.menuListDataArr settingsId:settingsId];
        
        // 遍历菜单是否包含对应功能模块
        [self.menuListDataArr enumerateObjectsUsingBlock:^(NSArray<SEGMenuListModel *> * _Nonnull sectionObj, NSUInteger sectionIdx, BOOL * _Nonnull sectionStop) {
            [sectionObj enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.widgetType.integerValue == SEGEnumShowTypeNewPGC) _hasNewPGC = YES;
                if (obj.widgetType.integerValue == SEGEnumShowTypeAD) _hasAD = YES;
                if (obj.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread_common) _hasCommonMenu = YES;
            }];
        }];
    });
    
    // PGC
    dispatch_group_async(group, queue, ^{
        if (_hasNewPGC) [self.pgcManager segPGCLayoutFromLocal];
    });
    
    // 广告
    dispatch_group_async(group, queue, ^{
        if (_hasAD) {
            NSArray *ad = [[SEGAdvlistManager sharedManager] segGetAdvertisementWithPostion:type];
            self.advertisementData = [self inner_segAdvertisementWithData:ad type:type];
        }
    });
    
    // 异步函数通知相应
    dispatch_group_notify(group, queue, ^{
        // 把广告、PGC等数据封装成SEGMenuListModel
        self.menuListDataArr = [self inner_packagingDataToSEGMenuListModelWithPositionType:type];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(_hasAD, _hasCommonMenu);
        });
    });
}

/// 请求网络菜单页面数据
/// @param menuSid 页面Id
/// @param action 页面编码
/// @param settingsId  导航菜单id
/// @param targetVC 控制器
/// @param type 广告类型
/// @param completion 回调
- (void)park_requestNetworkMenuForPageWithMenuSid:(NSString *)menuSid action:(NSString *)action settingsId:(NSString *)settingsId targetVC:(UIViewController *)targetVC positionType:(SEGAdvlistType)type completion:(park_menu_block)completion {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/terrace-service-app/terracePage/selectByPageId", nil];
    NSDictionary *params = @{};
    if (menuSid.length > 0) params = @{@"pageId":menuSid};
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_queue_create("com.uhome_park.menu.server", DISPATCH_QUEUE_CONCURRENT);
        
        __block BOOL _hasNewPGC = NO, _hasOldPGC = NO, _hasAD = NO, _hasCommonMenu = NO;
        // 【常用菜单】常用菜单容器
        __block SEGMenuListModel *_containerModel = nil;
        
        dispatch_barrier_async(queue, ^{
            // 获取所有菜单数据
            self.menuListDataArr = [SEGParkMenuListManager inner_responsePageDataWithAction:action isSuccessed:isSuccessed result:result];
            
            // 红点逻辑
            [self inner_bindRedDotWithData:self.menuListDataArr settingsId:settingsId];
            
            // 遍历菜单是否包含对应功能模块
            [self.menuListDataArr enumerateObjectsUsingBlock:^(NSArray<SEGMenuListModel *> * _Nonnull sectionObj, NSUInteger sectionIdx, BOOL * _Nonnull sectionStop) {
                [sectionObj enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj.widgetType.integerValue == SEGEnumShowTypeNewPGC) _hasNewPGC = YES;
                    if (obj.widgetType.integerValue == SEGEnumShowTypeHotPGC) _hasOldPGC = YES;
                    if (obj.widgetType.integerValue == SEGEnumShowTypeAD) _hasAD = YES;
                    if (obj.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread_common) {
                        _hasCommonMenu = YES;
                        _containerModel = obj;
                    }
                }];
            }];
        });
        
        // PGC
        dispatch_group_async(group, queue, ^{
            if (_hasNewPGC) {
                dispatch_group_enter(group);
                [self.pgcManager segRequestRecommendPGCFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    dispatch_group_leave(group);
                }];
            }
        });
        
        // 老PGC
        dispatch_group_async(group, queue, ^{
            if (_hasOldPGC) {
                dispatch_group_enter(group);
                WeakSelf;
                [self inner_requestOldPGCFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    NSArray<SEGMenuQuizTypeList*> *ret = result;
                    if (isSuccessed && ret && ret.count > 0) {
                        SEGMenuSideslipViewModel *data = [[SEGMenuSideslipViewModel alloc] init];
                        NSMutableArray *arrM = [NSMutableArray array];
                        for (SEGMenuQuizTypeList *object in ret) {
                            [arrM addObject:[[SEGUhomeMediator sharedInstance] seg_initOldPGCViewController:@{@"quizTypeId":object.id,
                                                                                                              @"forwordVC":targetVC,
                                                                                                              @"isRecommend":object.IsRecommend
                            }]];
                        }
                        data.contentDataSource = arrM;
                        data.titleDataSource = ret;
                        weakSelf.oldPgcData = data;
                    }
                    dispatch_group_leave(group);
                }];
            }
        });
        
        // 广告
        dispatch_group_async(group, queue, ^{
            if (_hasAD) {
                dispatch_group_enter(group);
                [self inner_requestADWithPositionType:type finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if(result) self.advertisementData = result;
                    if (!self.advertisementData || !self.advertisementData.adSource || self.advertisementData.adSource.count <= 0) {
                        NSArray *ad = [[SEGAdvlistManager sharedManager] segGetAdvertisementWithPostion:type];
                        self.advertisementData = [self inner_segAdvertisementWithData:ad type:type];
                    }
                    dispatch_group_leave(group);
                }];
            }
        });
        
        // 常用菜单数据
        dispatch_group_async(group, queue, ^{
            if (_hasCommonMenu) {
                [SEGParkMenuListManager inner_saveCommonMenuDataWithContainerModel:_containerModel];
            }
        });
        
        // 异步函数通知相应
        dispatch_group_notify(group, queue, ^{
            // 把广告、PGC等数据封装成SEGMenuListModel
            self.menuListDataArr = [self inner_packagingDataToSEGMenuListModelWithPositionType:type];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(_hasAD, _hasCommonMenu);
            });
        });
        
    }];
}

#pragma mark - 绑定红点关系
/// 保存父子级关系，用于打红点（把新菜单服务端返回的二维数据结构，改为一维数据结构。此方案无需重写消息模块绑定红点的逻辑）
/// @param data 菜单数据
/// @param settingsId 导航菜单id
- (void)inner_bindRedDotWithData:(NSArray<NSArray<SEGMenuListModel *> *> *)data settingsId:(NSString *)settingsId {
    NSMutableArray<SEGMenuListModel *> *dataArr = [NSMutableArray array];
    [data enumerateObjectsUsingBlock:^(NSArray<SEGMenuListModel *> * _Nonnull sectionObj, NSUInteger sectionIdx, BOOL * _Nonnull stop) {
        [sectionObj enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [dataArr addObject:obj];
        }];
    }];
    // 保存菜单父子级关系，用于打红点
    [[SEGUhomeMediator sharedInstance] seg_saveMenuList:@{@"array":dataArr, @"parentsSid":settingsId}];
}

#pragma mark - 菜单数据封装（控制row的数量）
/// 把广告、PGC等数据封装成SEGMenuListModel (此步骤和SEGMenuListManager处理菜单保持一致)
/// @param type 广告类型
- (NSArray<NSArray<SEGMenuListModel *> *> *)inner_packagingDataToSEGMenuListModelWithPositionType:(SEGAdvlistType)type {
    NSMutableArray<NSArray<SEGMenuListModel *> *> *tempMenuListData = [NSMutableArray array];
    [self.menuListDataArr enumerateObjectsUsingBlock:^(NSArray<SEGMenuListModel *> * _Nonnull disGroupArr, NSUInteger section, BOOL * _Nonnull sectionStop) {
        NSMutableArray *tempSectionData = [NSMutableArray array];
        [disGroupArr enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull menuModel, NSUInteger row, BOOL * _Nonnull stop) {
            if (menuModel.widgetType.integerValue == SEGEnumShowTypeAD) { // 广告
                SEGEnumAdvertismentType adType = SEGEnumAdvertismentType_NO;
                if (type == SEGAdvlistType_SERVER) adType = SEGEnumAdvertismentType_Find;
                menuModel.advertisementData = self.advertisementData;
                menuModel.advertisementData.adType = adType;
                menuModel.advertisementData.communityName = kAccountCommunityName;
                [tempSectionData addObject:menuModel];
                
            } else if (menuModel.widgetType.integerValue == SEGEnumShowTypeNewPGC) { // 新PGC
                [self.pgcManager.pgcModelArray enumerateObjectsUsingBlock:^(SEGPgcRecommendModel * _Nonnull pgcRecommendModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    SEGMenuListModel *model = [[SEGMenuListModel alloc] init];
                    model.widgetType = menuModel.widgetType;
                    model.rn = menuModel.rn;
                    model.disGroup = menuModel.disGroup;
                    model.pgcRecommendModel = pgcRecommendModel;
                    model.disGroupWidgetType = menuModel.disGroupWidgetType;
                    model.disGroupIsShow = menuModel.disGroupIsShow;
                    model.disGroupIsMargin = menuModel.disGroupIsMargin;
                    model.disGroupName = menuModel.disGroupName;
                    model.disGroupAndroidIcon = menuModel.disGroupAndroidIcon;
                    model.disGroupIosIcon = menuModel.disGroupIosIcon;
                    model.disGroupDesc = menuModel.disGroupDesc;
                    [tempSectionData addObject:model];
                }];
                
            } else if (menuModel.widgetType.integerValue == SEGEnumShowTypeHotPGC) { // 老PGC
                menuModel.oldPGCDataSource = self.oldPgcData;
                [tempSectionData addObject:menuModel];
                
            } else if (menuModel.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread_common) { // 常用菜单
                // 【常用菜单】获取常用应用
                SEGMenuListModel *commonMenuModel = [SEGMenuListCacheManager menuCache_getCommonMenuDataWithMaxCount:12 more:YES];
                [SEGParkMenuListManager inner_packagingRowToSEGMenuListModel:commonMenuModel sectionArr:tempSectionData row:4];
                
            } else if (menuModel.widgetType.integerValue == SEGEnumShowTypeTwoColumsSpread) { // 一行两列 平铺
                [SEGParkMenuListManager inner_packagingRowToSEGMenuListModel:menuModel sectionArr:tempSectionData row:2];
                
            } else if (menuModel.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread) { // 一行四列 平铺
                [SEGParkMenuListManager inner_packagingRowToSEGMenuListModel:menuModel sectionArr:tempSectionData row:4];
                
            } else {
                [tempSectionData addObject:menuModel];
            }
        }];
        [tempMenuListData addObject:tempSectionData];
    }];
    
    return tempMenuListData;
}
/// 将 一个 menuModel.childList 拆分成多个 menuModel.childList （次代码从MenuListManager中复制过来的）
/// @param menuModel 原数据
/// @param tempSectionData 临时数组, 存放menuModel
/// @param row  每个menuModel包含几个元素
+ (void)inner_packagingRowToSEGMenuListModel:(SEGMenuListModel *)menuModel sectionArr:(NSMutableArray *)tempSectionData row:(NSUInteger)row {
    __block SEGMenuListModel *model = [[SEGMenuListModel alloc]init];
    model.widgetType = menuModel.widgetType;
    model.rn = menuModel.rn;
    model.disGroup = menuModel.disGroup;
    model.disGroupWidgetType = menuModel.disGroupWidgetType;
    model.disGroupIsShow = menuModel.disGroupIsShow;
    model.disGroupIsMargin = menuModel.disGroupIsMargin;
    model.disGroupName = menuModel.disGroupName;
    model.disGroupAndroidIcon = menuModel.disGroupAndroidIcon;
    model.disGroupIosIcon = menuModel.disGroupIosIcon;
    model.disGroupDesc = menuModel.disGroupDesc;
    
    __block NSMutableArray *tmp = [NSMutableArray array];
    [menuModel.childList enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull objD, NSUInteger idxD, BOOL * _Nonnull stopD) {
        [tmp addObject:objD];
        model.childList = tmp ;
        if (idxD%row == (row - 1)) {
            model.childList = [tmp copy];
            //新建
            model = [[SEGMenuListModel alloc]init];
            model.widgetType = menuModel.widgetType;
            model.rn = menuModel.rn;
            model.disGroup = menuModel.disGroup;
            model.disGroupWidgetType = menuModel.disGroupWidgetType;
            model.disGroupIsShow = menuModel.disGroupIsShow;
            model.disGroupIsMargin = menuModel.disGroupIsMargin;
            model.disGroupName = menuModel.disGroupName;
            model.disGroupAndroidIcon = menuModel.disGroupAndroidIcon;
            model.disGroupIosIcon = menuModel.disGroupIosIcon;
            model.disGroupDesc = menuModel.disGroupDesc;
            
            tmp = [NSMutableArray array];
        }
        if (![tempSectionData containsObject:model]) {
            if (model.childList.count > 0) {
                [tempSectionData addObject:model];
            }
        }
    }];
}

#pragma mark - 查询菜单数据中是否有H5缴费菜单
/// 查询菜单数据中是否有H5缴费菜单
- (SEGMenuListModel *)park_getWebBillPayURL {
    __block SEGMenuListModel *model = nil;
    [self.menuListDataArr enumerateObjectsUsingBlock:^(NSArray<SEGMenuListModel *> * _Nonnull sectionObj, NSUInteger sectionIdx, BOOL * _Nonnull stop) {
        [sectionObj enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.isWebBillPay.integerValue == 1) {
                model = obj;
                *stop = YES;
            }
        }];
    }];
    return model;
}

#pragma mark - 广告请求
/// 请求广告数据
/// @param type 广告类型
/// @param finished 回调
- (void)inner_requestADWithPositionType:(SEGAdvlistType)type finished:(SEGNetworkReponse)finished {
    [[SEGAdvlistManager sharedManager] segRequestAdvlistWithPositionType:type completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
        if (isSuccessed) {
            SEGAdvertisementViewModel *data = [self inner_segAdvertisementWithData:result type:type];
            finished(isSuccessed,data,codeType,errorMessage);
            return;
        }
        finished(NO,nil,codeType,errorMessage);
    }];
}
- (SEGAdvertisementViewModel *)inner_segAdvertisementWithData:(NSArray<SEGAdvertismentModel *> *)dt type:(SEGAdvlistType)type {
    SEGAdvertisementViewModel *adData = [[SEGAdvertisementViewModel alloc] init];
    adData.adSource = dt;
    adData.communityName = kAccountCommunityName;
    if (type == SEGAdvlistType_SERVER) adData.locationShowType = SEGEnumCommunityLocationViewType_Location;
    return adData;
}

#pragma mark - 老PGC请求
/// 请求老PGC列表
/// @param finished 回调
- (void)inner_requestOldPGCFinished:(SEGNetworkReponse)finished {
    [[SEGQuiztypelistManager sharedManager] requestQuiztypelistWithParameters:@{@"isPgcType":@"1"} finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            NSDictionary *data = [result valueForKey:@"data"];
            if (data && [data isKindOfClass:[NSDictionary class]]) {
                NSArray *quizTypeList = [data valueForKey:@"quizTypeList"];
                if (quizTypeList && [quizTypeList isKindOfClass:[NSArray class]]) {
                    NSMutableArray<SEGMenuQuizTypeList*> *retM = [NSMutableArray array];
                    
                    SEGMenuQuizTypeList* tmp = [[SEGMenuQuizTypeList alloc] init];
                    tmp.quizDesc = @"推荐";
                    tmp.IsRecommend = @"1";
                    tmp.id = @"-1";
                    [retM addObject:tmp];
                    
                    for (NSDictionary *object in quizTypeList) {[retM addObject:[SEGMenuQuizTypeList yy_modelWithDictionary:object]];}
                    finished(YES,retM,codeType,errorMessage);
                    return;
                }
            }
        }
        finished(NO,nil,codeType,errorMessage);
    }];
}

#pragma mark - 保存常用菜单数据到本地
/// 保存常用菜单数据到本地
/// @param containerModel 容器
+ (void)inner_saveCommonMenuDataWithContainerModel:(SEGMenuListModel *)containerModel {
    // 1). 获取所有常用菜单数据
    NSArray<SEGMenuListModel *> *allCommonDataArr = [SEGMenuListCacheManager menuCache_getAllCommonMenuListData];
    // 2). 获取常用应用
    SEGMenuListModel *commonMenuModel = [SEGMenuListCacheManager menuCache_getCommonMenuData];
    NSMutableArray<SEGMenuListModel *> *newChildListData = [NSMutableArray<SEGMenuListModel *> array];
    // 3). 保存服务端最新数据
    if (commonMenuModel.childList.count == 0) { // 3_a). 不存在常用应用, 保存服务端默认常用菜单（取前7条）
        [allCommonDataArr enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx < 7) {
                [newChildListData addObject:obj];
            }
        }];
    } else { // 3_b). 存在常用应用
        [commonMenuModel.childList enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [allCommonDataArr enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull serverObj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.settingsId.integerValue == serverObj.settingsId.integerValue) {
                    [newChildListData addObject:serverObj];
                }
            }];
        }];
    }
    // 4). 本地不存在"更多按钮", 新增
    if (![newChildListData.lastObject.action isEqualToString:kActionCOMMON_MENULIST]) {
        SEGMenuListModel *model = [SEGMenuListModel new];
        model.action = kActionCOMMON_MENULIST;
        model.iosicon = @"commonMenu_more";
        model.serviceName = @"更多应用";
        model.disGroupName = commonMenuModel.disGroupName;
        [newChildListData addObject:model];
    }
    // 5). 更新容器, 绑定常用应用数据
    commonMenuModel = containerModel;
    commonMenuModel.childList = [newChildListData copy];
    // 6). 更新本地常用应用
    [SEGMenuListCacheManager menuCache_saveCommonMenuWithData:commonMenuModel];
}

#pragma mark - tabBar和菜单页面数据解析
/// 解析底部tabBar菜单数据（缓存菜单数据）
/// @param action 编码
/// @param isSuccessed 是否成功
/// @param result 菜单数据
+ (NSArray<SEGMenuListModel *> *)inner_responseTabBarDataWithAction:(NSString *)action isSuccessed:(BOOL)isSuccessed result:(id)result {
    NSArray<SEGMenuListModel *> *ret = [NSArray array];
    // 请求失败
    if (!isSuccessed) {
        ret = [SEGMenuListCacheManager menuCache_getMenuListDataWithAction:action];
        return ret;
    }
    
    // 请求成功
    NSMutableArray<SEGMenuListModel *> *arrM = [NSMutableArray array];
    NSDictionary *data = [[result allKeys] containsObject:@"data"] ? [result valueForKey:@"data"] : nil;
    if ([[data allKeys] containsObject:@"navigate"]) {
        SEGParkMenuTabBarModel *model = [SEGParkMenuTabBarModel yy_modelWithDictionary:data[@"navigate"]];
        // 新菜单数据映射为老菜单数据
        [model.navigateMenuList enumerateObjectsUsingBlock:^(SEGParkMenuTabBarListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SEGMenuListModel *model = [[SEGMenuListModel alloc] init];
            model.menuSid = obj.pageId;
            model.settingsId = [NSString stringWithFormat:@"T_%@", obj.id];
            model.action = obj.pageCode;
            model.serviceName = obj.menuName;
            model.resCode = obj.msgCode;
            model.iosiconpre = obj.iosClickUrl;
            model.iosicon = obj.iosDefaultUrl;
            model.iosDarkClickIcon = obj.iosDarkClickUrl;
            model.iosDarkUnclickIcon = obj.iosDarkDefaultUrl;
            
            [arrM addObject:model];
        }];
    }
    
    // 缓存tabbar数据
    [SEGMenuListCacheManager menuCache_saveMenuListData:arrM action:action];
    
    ret = [arrM copy];
    return ret;
}

/// 解析页面菜单数据（缓存菜单数据）
/// @param action 编码
/// @param isSuccessed 是否成功
/// @param result 菜单数据
+ (NSArray<NSArray<SEGMenuListModel *> *> *)inner_responsePageDataWithAction:(NSString *)action isSuccessed:(BOOL)isSuccessed result:(id)result {
    NSArray<NSArray<SEGMenuListModel *> *> *ret = [NSArray array];
    // 请求失败
    if (!isSuccessed) {
        ret = [SEGMenuListCacheManager sany_menuCache_getMenuListDataWithAction:action];
        return ret;
    }
    
    // 请求成功
    NSMutableArray<NSMutableArray<SEGMenuListModel *> *> *arrM = [NSMutableArray array];
    NSDictionary *data = [[result allKeys] containsObject:@"data"] ? [result valueForKey:@"data"] : nil;
    if ([[data allKeys] containsObject:@"page"]) {
        SEGParkMenuPageModel *model = [SEGParkMenuPageModel yy_modelWithDictionary:data[@"page"]];
        
        // 新菜单模型映射为老菜单模型
        // 顶部导航 (sany+v1.4.0此版本只支持99002导航)
        if (model.topComponent) {
            SEGMenuListModel *navModel = [[SEGMenuListModel alloc] init];
            navModel.settingsId = @"NewMenu_99002";
            navModel.serviceName = model.topComponent.name;
            NSUInteger navWidgetType = [SEGParkMenuListManager inner_mapWidgetTypeWithSanyType:model.topComponent.styleCode];
            navModel.widgetType = ValueToString(@(navWidgetType));
            navModel.isShowLine = @"2";
            navModel.action = @"cn.segi.uhome.action.MSG_CENTER";
            navModel.resCode = @"RES_MESSAGE";
            
            NSMutableArray *navArr = [NSMutableArray array];
            [navArr addObject:navModel];
            
            [arrM addObject:navArr];
        }
        
        // 【常用菜单】记录常用菜单不同的组名，添加上disGroup分组
        NSMutableArray *commonDisGroupNameArr = [NSMutableArray array];
        
        // 页面菜单数据（sany+v1.4.0新菜单数据映射为老菜单数据）
        [model.content enumerateObjectsUsingBlock:^(SEGParkMenuContentModel * _Nonnull sectionObj, NSUInteger sectionIdx, BOOL * _Nonnull sectionStop) {
            SEGMenuListModel *sectionModel = [SEGMenuListModel new];
            sectionModel.disGroupIsShow = sectionObj.name.length > 0 ? @"1":@"0";
            sectionModel.disGroupName = sectionObj.name;
            sectionModel.disGroupWidgetType = ValueToString(@(SEGMenuGroupNormal));
            NSUInteger widgetType = [SEGParkMenuListManager inner_mapWidgetTypeWithSanyType:sectionObj.styleCode];
            sectionModel.widgetType = ValueToString(@(widgetType));
            sectionModel.disGroup = sectionObj.componentId;
            sectionModel.disGroupIsMargin = [action isEqualToString:@"TAB_SERVICE"] ? @"1":@"2";
            
            // 新菜单物业公告菜单不会返回settingsId，本地添加一个，否则跳转时候条件不满足，无法跳转
            if (sectionModel.widgetType.integerValue == SEGEnumShowTypePropertyNotification) {
                sectionModel.settingsId = @"NewMenu_30001";
                sectionModel.resCode = @"RES_PROPERTY_PUBLIC_SERVICE";
            }
            
            //  新菜单无法配置个人头部控件的跳转方式，只能本地写死action
            if (sectionModel.widgetType.integerValue == SEGEnumShowTypeHeader) {
                sectionModel.action = @"cn.segi.uhome.action.PROFILE";
            }
            
            NSMutableArray *childListArr = [NSMutableArray new];
            [sectionObj.menuInfoList enumerateObjectsUsingBlock:^(SEGParkMenuInfoListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                SEGMenuListModel *rowModel = [[SEGMenuListModel alloc] init];
                
                // 【鉴权】鉴权字段
                rowModel.authCode = obj.funCode;
                rowModel.needAuth = obj.funType;
                // 服务类型功能 需要app过滤权限
                if (rowModel.needAuth && [rowModel.needAuth isEqualToString:@"1"]) {
                    SEGQueryauthinfoDataModel *data = [SEGQueryauthinfoManager sharedManager].QueryAuthInfo.data;
                    if (!data.menuAuth || ![data.menuAuth containsObject:rowModel.authCode]) { // 无权限，跳出本次循环
                        return;
                    }
                }
                
                // 组头信息
                rowModel.disGroupIsShow = sectionModel.disGroupIsShow;
                rowModel.disGroupName = sectionModel.disGroupName;
                rowModel.disGroupWidgetType = sectionModel.disGroupWidgetType;
                rowModel.disGroupIsMargin = sectionModel.disGroupIsMargin;
                rowModel.widgetType = sectionModel.widgetType;
                rowModel.disGroup = sectionModel.disGroup;
                // 单个菜单信息
                rowModel.settingsId = obj.id;
                rowModel.serviceName = obj.menuName;
                rowModel.serviceDesc = obj.menuDesc;
                rowModel.resCode = obj.msgCode;
                rowModel.action = obj.url;
                rowModel.iosiconpre = obj.iosClickUrl;
                rowModel.iosicon = obj.iosDefaultUrl;
                rowModel.iosDarkClickIcon = obj.iosDarkClickUrl;
                rowModel.iosDarkUnclickIcon = obj.iosDarkDefaultUrl;
                
                // 新菜单H5缴费编码
                if ([obj.funCode isEqualToString:@"webBillPay"]) {
                    rowModel.isWebBillPay = @"1";
                }
                
                // 【常用菜单】常用菜单需要根据组标题进行分组
                if (sectionModel.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread_common) {
                    rowModel.disGroupName = obj.extraInfo;
                    // extraInfo可能为@"", 也需要占一组
                    if (![commonDisGroupNameArr containsObject:rowModel.disGroupName]) {
                        [commonDisGroupNameArr addObject:rowModel.disGroupName];
                    }
                }
                
                if (obj.integrationType.integerValue == 2) { // H5
                    rowModel.type = @"1";
                    
                    NSDictionary *funExtraInfoDict = [NSJSONSerialization JSONObjectWithData:[obj.funExtraInfo dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
                    if ([funExtraInfoDict.allKeys containsObject:@"h5Type"]) {
                        rowModel.isBrowser = funExtraInfoDict[@"h5Type"];
                    } else {
                        rowModel.isBrowser = @"0";
                    }
                } else if (obj.integrationType.integerValue == 3) { // 小程序
                    rowModel.type = @"3";
                    
                    NSDictionary *funExtraInfoDict = [NSJSONSerialization JSONObjectWithData:[obj.funExtraInfo dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
                    if ([funExtraInfoDict.allKeys containsObject:@"wxUserName"]) {
                        rowModel.wxUserName = funExtraInfoDict[@"wxUserName"];
                    }
                    if ([funExtraInfoDict.allKeys containsObject:@"wxPath"]) {
                        rowModel.wxPath = funExtraInfoDict[@"wxPath"];
                    }
                    if ([funExtraInfoDict.allKeys containsObject:@"wxMiniProgramType"]) {
                        rowModel.wxMiniProgramType = funExtraInfoDict[@"wxMiniProgramType"];
                    }
                } else { // 原生
                    rowModel.type = @"0";
                }
                
                [childListArr addObject:rowModel];
            }];
            
            //  【常用菜单】常用菜单数据添加disGroup
            if (sectionModel.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread_common) {
                [commonDisGroupNameArr enumerateObjectsUsingBlock:^(NSString *disGroupName, NSUInteger disGroupIdx, BOOL * _Nonnull stop) {
                    [childListArr enumerateObjectsUsingBlock:^(SEGMenuListModel *rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([disGroupName isEqualToString:rowModel.disGroupName]) {
                            rowModel.widgetType = ValueToString(@(SEGEnumShowTypeFourColumsSpread)); // 老的常用菜单20013组表示占位，里面的数据是20011，改为和老常用菜单数据一样
                            rowModel.disGroup = ValueToString(@(disGroupIdx));
                            rowModel.rn = ValueToString(@(idx));
                            rowModel.disGroupIsShow = disGroupName.length > 0 ? @"1":@"0";
                            rowModel.disGroupWidgetType = ValueToString(@(SEGMenuGroupColorLine)); // 固定常用菜单页面组样式
                        }
                    }];
                }];
                
                // 【常用菜单】保存常用菜单所有数据
                [SEGMenuListCacheManager menuCache_saveAllCommonMenuListWithData:childListArr];
            }
            
            
            NSMutableArray *_sectionArr = [NSMutableArray array];
            // 只有以下的菜单类型才需要把数据封装到childList中
            if(sectionModel.widgetType.integerValue == SEGEnumShowTypeTwoColumsSpread ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeTwoColums ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeFourColums ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeThreeColums ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeThreeColumsSpread ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeFiveColumsSpread ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeCircleAndRect ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeHorizontalColums ||
               sectionModel.widgetType.integerValue == SEGEnumShowTypeFourColumsSpread_common) {
                // 把相同widgetType的菜单数据装在一个模型的childList中
                sectionModel.childList = [childListArr copy];
                [_sectionArr addObject:sectionModel];
                
            } else if (sectionModel.widgetType.integerValue == SEGEnumShowTypeHouseAuthentication) { // 一行一列
                _sectionArr = [childListArr copy];
                
            } else { // 其他类型的菜单
                [_sectionArr addObject:sectionModel];
            }
            
            [arrM addObject:_sectionArr];
        }];
    }
    
    // 缓存页面菜单数据
    [SEGMenuListCacheManager sany_menuCache_saveMenuListData:arrM action:action];
    
    ret = [arrM copy];
    return ret;
}

#pragma mark - 新菜单映射老菜单
/// 将新的菜单类型映射为saas的widgetTyep
/// @param widgetTyep 菜单类型
+ (NSUInteger)inner_mapWidgetTypeWithSanyType:(NSString *)widgetTyep {
    if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.nav_community_message]) {
        return SEGEnumShowTypeNavigationBar_99002;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.ad_banner]) {
        return SEGEnumShowTypeAD;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.property_notification]) {
        return SEGEnumShowTypePropertyNotification;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.edit_menu]) {
        return SEGEnumShowTypeFourColumsSpread_common;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.menu_two_column]) {
        return SEGEnumShowTypeTwoColumsSpread;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.pgc_tab]) {
        return SEGEnumShowTypeHotPGC;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.menu_four_column]) {
        return SEGEnumShowTypeFourColumsSpread;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.person_info]) {
        return SEGEnumShowTypeHeader;
    } else if ([widgetTyep isEqualToString:SEGParkMenuWidgetType.menu_one_column]) {
        return SEGEnumShowTypeHouseAuthentication;
    }
    
    return 0;
}

#pragma mark - Setter
+ (void)setMenuListTab:(NSArray<SEGMenuListModel *> *)menuListTab {
    if (menuListTab != _menuListTab) {
        _menuListTab = [menuListTab copy];
    }
}
#pragma mark - Getter
+ (NSArray<SEGMenuListModel *> *)menuListTab {
    if (!_menuListTab) _menuListTab = [NSArray new];
    return _menuListTab;
}
- (NSArray<NSArray<SEGMenuListModel *> *> *)menuListDataArr {
    if (!_menuListDataArr) _menuListDataArr = [NSArray array];
    return _menuListDataArr;
}
- (SEGPgcManager *)pgcManager {
    if (!_pgcManager) _pgcManager = [SEGPgcManager new];
    return _pgcManager;
}

@end
